package com.czk.protocol.http;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.servlets.DefaultServlet;
import org.apache.catalina.startup.Tomcat;

/**
 * 使用内嵌的tomcat
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/14 16:13
 */
public class HttpServer {
    public void start(String hostname, Integer port) {
        // 定义tomcat服务器
        Tomcat tomcat=new Tomcat();
        // 拿到服务器
        Server server = tomcat.getServer();
        // 拿到service服务
        Service service = server.findService("Tomcat");
        // 拿到connector
        Connector connector=new Connector();
        // 绑定端口
        connector.setPort(port);
        // 创建引擎
        Engine engine=new StandardEngine();
        // 设置主机
        engine.setName(hostname);
        Host host=new StandardHost();
        host.setName(hostname);
        // 设置context
        String contextPath="";
        Context context=new StandardContext();
        context.setPath(contextPath);
        // 设置监听器
        context.addLifecycleListener(new Tomcat.FixContextListener());
        // 设置层级关系
        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        tomcat.addServlet(contextPath,"dispatcher",new DispatcherServlet());
        context.addServletMappingDecoded("/*","dispatcher");
        // 启动tomcat
        try {
            tomcat.start();
            tomcat.getServer().await();
        }catch (LifecycleException ex){
            ex.printStackTrace();
        }
    }
}
